package com.example.grpc.auto.configuration;

import com.example.grpc.GreetingService;
import com.example.grpc.GreetingServiceGrpc;
import com.example.grpc.GreetingServiceOuterClass;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;

import java.io.Closeable;
import java.io.IOException;

/**
 * @author fengyang(yueny09 @ 163.com)
 * @date 2022年05月07日 下午7:27
 */
public class DemoEnableAutoConfiguration implements InitializingBean, Closeable {
    private ManagedChannel managedChannel;

    @Override
    public void afterPropertiesSet() throws Exception {
        // Channel is the abstraction to connect to a service endpoint
        // Let's use plaintext communication because we don't have certs
        final ManagedChannel channel = ManagedChannelBuilder.forTarget("localhost:8081")
                .usePlaintext(true)
                .build();

        this.managedChannel = channel;
    }

    @Override
    public void close() throws IOException {
        // A Channel should be shutdown before stopping the process.
        managedChannel.shutdownNow();
    }

    @Bean
    public GreetingService greetingService() {
        return new GreetingService() {
            @Override
            public GreetingServiceOuterClass.HelloResponse greeting(GreetingServiceOuterClass.HelloRequest request) {
                // It is up to the client to determine whether to block the call
                // Here we create a blocking stub, but an async stub,
                // or an async stub with Future are always possible.
                GreetingServiceGrpc.GreetingServiceBlockingStub stub =
                        GreetingServiceGrpc.newBlockingStub(managedChannel);

                // Finally, make the call using the stub
                GreetingServiceOuterClass.HelloResponse response =
                        stub.greeting(request);

                System.out.println(response);

                return response;
            }
        };
    }

}
